package kafdrop.util;


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONObject;

import java.util.HashSet;
import java.util.Set;

/**
 * @author jackybian
 * @date 2020/12/4
 */
public class JsonUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        JsonUtil.objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        JsonUtil.objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
        JsonUtil.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        JsonUtil.objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }


    public static JsonNode jsonNodeOf(String json) {
        return json2Bean(json, JsonNode.class);
    }

    public static <T> T json2Bean(String json, Class<T> clazz) {
        if (json == null) {
            try {
                return clazz.newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T object2Bean(Object from, Class<T> to) {
        return objectMapper.convertValue(from, to);
    }

    private static final ObjectWriter prettyWriter = JsonUtil.objectMapper.writerWithDefaultPrettyPrinter();

    public static String toJsonPrettyString(Object value) throws JsonProcessingException {
        return prettyWriter.writeValueAsString(value);
    }

    public static String toJsonString(Object value) throws JsonProcessingException {
        return objectMapper.writeValueAsString(value);
    }

    public static String toJsonStringNotException(Object value) {
        try {
            return objectMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            return null;
        }
    }

    public static String toJsonPrettyStringNotException(Object value) {
        try {
            //日志打印行数过多
            return prettyWriter.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            return null;
        }
    }
}
